package com.umbrella.manage.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;
import org.springframework.boot.context.embedded.undertow.UndertowBuilderCustomizer;
import org.springframework.boot.context.embedded.undertow.UndertowEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import io.undertow.servlet.api.SecurityConstraint;
import io.undertow.servlet.api.SecurityInfo;
import io.undertow.servlet.api.TransportGuaranteeType;
import io.undertow.servlet.api.WebResourceCollection;

/**
 *
 *
 * @author Wan, ChuanLong @ 08/03/2018
 */

@Configuration
public class SSLConfig {

    @Value("${server.http.port}")
    private int httpPort;
    @Value("${server.port}")
    private int httpsPort;
    
	@Bean
	public EmbeddedServletContainerFactory servletContainer() {
		
		UndertowEmbeddedServletContainerFactory undertowFactory = new UndertowEmbeddedServletContainerFactory();
		
		// 监听HTTP端口
		undertowFactory.addBuilderCustomizers((UndertowBuilderCustomizer) builder -> builder.addHttpListener(httpPort, "0.0.0.0"));
		
		// 将HTTP端口重定向到HTTPS的端口
		undertowFactory.addDeploymentInfoCustomizers(deploymentInfo -> {
			deploymentInfo
					.addSecurityConstraint(new SecurityConstraint()
							.addWebResourceCollection(new WebResourceCollection().addUrlPatterns("/api/*", "/res/*"))
							.setTransportGuaranteeType(TransportGuaranteeType.CONFIDENTIAL)
							.setEmptyRoleSemantic(SecurityInfo.EmptyRoleSemantic.PERMIT))
					.setConfidentialPortManager(exchange -> httpsPort);
		});
		
		return undertowFactory;
	}
}
